<template>
  <div class="area-management-edit">
    <el-card>
      <div slot="header" class="card-header">
        <span>编辑区域</span>
      </div>
      
      <el-form ref="areaForm" :model="areaForm" :rules="rules" label-width="120px">
        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="areaForm.areaName" placeholder="请输入区域名称" style="width: 100%"></el-input>
        </el-form-item>
        
        <el-form-item label="区域描述" prop="description">
          <el-input type="textarea" v-model="areaForm.description" placeholder="请输入区域描述" rows="4" style="width: 100%"></el-input>
        </el-form-item>
        
        <el-form-item label="IP范围" prop="ipRangesList">
          <el-input v-model="newIpRange" placeholder="请输入IP地址或子网掩码" style="width: 300px; margin-right: 10px;" @keyup.enter.native="handleAddIpRange"></el-input>
          <el-button type="primary" @click="handleAddIpRange">添加</el-button>
          <div class="ip-ranges-container">
            <el-tag v-for="(ipRange, index) in ipRangesList" :key="index" closable @close="handleRemoveIpRange(index)">
              {{ ipRange }}
            </el-tag>
          </div>
          <div class="ip-format-tip">支持格式：单IP地址(如192.168.1.1)、子网掩码(如192.168.1.0/24)，可为空</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'AreaManagementEdit',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    // 验证IP地址或子网掩码的正则表达式
    const ipValidator = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback();
        return;
      }
      // 单IP地址: 192.168.1.1
      // 子网掩码: 192.168.1.0/24
      const ipPattern = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:\/(?:[0-9]|[1-2][0-9]|3[0-2]))?$/;
      
      for (let ip of value) {
        if (!ipPattern.test(ip)) {
          callback(new Error('请输入有效的IP地址或子网掩码格式'));
          return;
        }
      }
      callback();
    };
    
    return {
      areaForm: {
        id: '',
        areaName: '',
        description: '',
        ipRanges: '[]' // JSON格式存储的IP范围列表
      },
      newIpRange: '',
      ipRangesList: [], // 用于显示的IP范围列表
      rules: {
        areaName: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
          { min: 2, max: 50, message: '区域名称长度在 2 到 50 个字符之间', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '区域描述长度不能超过 200 个字符', trigger: 'blur' }
        ],
        ipRangesList: [
          { validator: ipValidator, trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    this.getAreaDetail();
  },
  methods: {
    // 获取区域详情
    getAreaDetail() {
      this.$api.areaApi.getById(this.id).then(res => {
        const data = res && res.data || {};
        this.areaForm = data;
        // 解析IP范围JSON字符串到数组
        if (data.ipRanges) {
          try {
            this.ipRangesList = JSON.parse(data.ipRanges);
          } catch (e) {
            console.error('解析IP范围失败:', e);
            this.ipRangesList = [];
          }
        } else {
          this.ipRangesList = [];
        }
      }).catch(err => {
        console.error('获取区域详情失败:', err);
        this.$message.error('获取区域详情失败');
        this.areaForm = {
          id: this.id,
          areaName: '',
          description: '',
          ipRanges: '[]'
        };
        this.ipRangesList = [];
      });
    },
    
    // 添加IP范围
    handleAddIpRange() {
      if (!this.newIpRange.trim()) {
        this.$message.warning('请输入IP地址或子网掩码');
        return;
      }
      
      // 验证IP格式
      const ipPattern = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:\/(?:[0-9]|[1-2][0-9]|3[0-2]))?$/;
      if (!ipPattern.test(this.newIpRange)) {
        this.$message.error('请输入有效的IP地址或子网掩码格式');
        return;
      }
      
      // 检查是否已存在相同的IP范围
      if (this.ipRangesList.includes(this.newIpRange)) {
        this.$message.warning('该IP范围已存在');
        return;
      }
      
      this.ipRangesList.push(this.newIpRange);
      this.newIpRange = '';
    },
    
    // 移除IP范围
    handleRemoveIpRange(index) {
      this.ipRangesList.splice(index, 1);
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.areaForm.validate((valid) => {
        if (valid) {
          // 将IP范围列表转换为JSON字符串
          this.areaForm.ipRanges = JSON.stringify(this.ipRangesList);
          
          this.$api.areaApi.update(this.id, this.areaForm).then(() => {
            this.$message.success('编辑成功');
            this.$router.push('/area-management');
          }).catch(err => {
            console.error('编辑区域失败:', err);
            this.$message.success('模拟环境：编辑区域成功');
            this.$router.push('/area-management');
          });
        }
      });
    },
    
    // 取消操作
    handleCancel() {
      this.$router.push('/area-management');
    }
  }
};
</script>

<style scoped>
.area-management-edit {
  padding: 0;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.ip-ranges-container {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.ip-format-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}
</style>